<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>opencv  pyrUp  contours</title>
    <!-- <script src='https://docs.opencv.org/版本号/opencv.js'></script> -->
    <!-- OpenCV.js 4.5.5 版本 -->
    <!-- <script src='https://docs.opencv.org/4.5.5/opencv.js'></script> -->

    <!-- <script src='./opencv_4.5.5.js' type="module"></script> -->

    <!-- You may want to load opencv.js asynchronously by async attribute in <script> tag. To be notified when opencv.js is ready, you can register a callback to onload attribute. -->
    <script src="./9_def_rune_tool_2/common/utils/my_opencv_fun.js"></script>
    <script async src="./opencv_4.5.5.js" onload="openCvReady()" type="text/javascript"></script>

    <canvas style="display: block;" id="imageCanvasInput1" width="100" height="100"></canvas>

    <canvas style="display: none;" id="imageCanvasInput2" width="70" height="70"></canvas>

    <!-- 放大图 -->
    <canvas style="display: none;" id="img_amplify1" width="100" height="100"></canvas>
    <canvas style="display: none;" id="img_amplify2" width="100" height="100"></canvas>
    <canvas style="display: none;" id="img_amplify3" width="100" height="100"></canvas>

    <!-- 绘制轮廓 -->
    <canvas style="display: block;" id="img1" width="100" height="100"></canvas>
    <canvas style="display: block;" id="img2" width="100" height="100"></canvas>
    <canvas style="display: block;" id="img3" width="100" height="100"></canvas>

</head>

<body style="background-color: #260853;">
    <!-- <script type="module">
        import * as cv from './opencv_4.5.5.js';
        console.log(cv);
    </script> -->
    <script>
        // console.log("xxx", window.$mocvf);
        async function openCvReady() {
            // 脚本加载完成
            // console.log(cv);
            // opencv.js 在真正初始化之前加载并触发 onload 事件。为了等到 opencv.js 真正准备好，opencv.js 提供了一个挂机“onRuntimeInitialized”。像这样使用它：

            // var img1 = new Image();
            // img.crossOrigin = 'anonymous';
            // img1.src = './img1.png';
            // console.log(1);

            // var src1 = "./img1.png";
            // var src2 = "./img2.png";

            // var src1 = "./icons.png";
            var src1 = "./9_def_rune_tool_2/imgs/test/bag_rune.png";
            // var src1 = "./9_def_rune_tool_2/imgs/test/bag_rune2.png";
            // var src2 = "./icon.png";
            var src2 = "./img3.png";
            await Promise.all([await loadImg(src1).then(img1 => {
                // console.log(img1);
                var canvas1 = document.getElementById('imageCanvasInput1');
                var ctx1 = canvas1.getContext('2d');
                // img1.onload = function () {
                //     ctx1.drawImage(img1, 0, 0);
                // }
                canvas1.width = img1.width;
                canvas1.height = img1.height;
                ctx1.drawImage(img1, 0, 0);


                // var canvas3 = document.getElementById('canvasOutput');
                // canvas3.width = img1.width;
                // canvas3.height = img1.height;
                // var ctx3 = canvas3.getContext('2d');
                // ctx3.drawImage(img1, 0, 0);

                // console.log(12);
            }), await loadImg(src2).then(img2 => {
                // console.log(img2);
                // var canvas2 = document.getElementById('imageCanvasInput2');
                // canvas2.width = img2.width;
                // canvas2.height = img2.height;
                // var ctx2 = canvas2.getContext('2d');
                // ctx2.drawImage(img2, 0, 0);
                // console.log(13);
            })]);

            // console.log(2);
            cv['onRuntimeInitialized'] = () => {
                console.log("xxx");
                // 读取原始图像
                let image = cv.imread("imageCanvasInput1");


                /*
                // 放大
                let img1 = image.clone();
                let img2 = image.clone();
                let img3 = image.clone();
                let size1 = new cv.Size(image.cols * 10, image.rows * 10);

                cv.resize(img1, img1, size1);
                cv.resize(img2, img2, size1, 0, 0, cv.INTER_CUBIC); //更清晰点

                cv.imshow("img_amplify1", img1);
                cv.imshow("img_amplify2", img2);

                let size2 = new cv.Size(0, 0);// 没啥用

                cv.pyrUp(img3, img3, size2, cv.BORDER_DEFAULT);
                cv.imshow("img_amplify3", img3);
                */


                // 绘制轮廓
                let img1 = image.clone();
                let size1 = new cv.Size(image.cols * 4, image.rows * 4);
                cv.resize(img1, img1, size1);
                cv.imshow("imageCanvasInput1", img1);

                /*
                cv.cvtColor(img1, img1, cv.COLOR_RGBA2GRAY, 0);
                // cv.imshow('img1', img1);
                cv.threshold(img1, img1, 140, 200, cv.THRESH_BINARY);
                // cv.imshow('img2', img1);
                cv.imshow('img1', img1);
                */

                // /*
                let arr_l = [100, 120, 100, 255];
                let arr_h = [200, 200, 200, 255];

                let img2_b_w = img1.clone();
                let low_hsv_src = new cv.Mat(img2_b_w.rows, img2_b_w.cols, img2_b_w.type(), arr_l);
                let high_hsv_src = new cv.Mat(img2_b_w.rows, img2_b_w.cols, img2_b_w.type(), arr_h);
                cv.inRange(img2_b_w, low_hsv_src, high_hsv_src, img2_b_w); // cv.CV_8U
                // img2_b_w.convertTo(img2, cv.CV_8UC4);
                cv.imshow("img1", img2_b_w);
                // img1 = cv.imread("img1"); // cv.CV_8U转化成 cv.CV_8UC4

                img1 = img2_b_w.clone();
                // */

                // return;
                let contours = new cv.MatVector();
                let hierarchy = new cv.Mat();

                let img2 = cv.Mat.zeros(img1.rows, img1.cols, cv.CV_8UC3);


                // cv.findContours(img1, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);
                cv.findContours(img1, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);
                // cv.findContours(img1, contours, hierarchy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE);
                // return;
                console.log(contours.size());
                let count = 0;
                for (let i = 0; i < contours.size(); ++i) {

                    let hier = hierarchy.intPtr(0, i);
                    let cnt = contours.get(i);
                    let order_txt_color = new cv.Scalar(Math.round(Math.random() * 255), Math.round(Math
                        .random() * 255), Math.round(Math.random() * 255));
                    cv.drawContours(img2, contours, i, order_txt_color, 1, cv.LINE_8, hierarchy, 100);


                    // 外接矩形绘制
                    let rect = cv.boundingRect(cnt);
                    if(rect.width < 20 || rect.height < 20){
                        continue;
                    }
                    count++;
                    let point1 = new cv.Point(rect.x, rect.y);
                    let point2 = new cv.Point(rect.x + rect.width, rect.y + rect.height);

                    let point = new cv.Point(rect.x + 5, rect.y  - 5);
                    cv.putText(img2, count + "", point, cv.FONT_HERSHEY_SIMPLEX, 0.4, order_txt_color, 1, cv
                        .LINE_4); // 标序号

                    cv.rectangle(img2, point1, point2, order_txt_color, 1, cv.LINE_AA, 0); // 绘制外接矩形
                    cnt.delete();
                }
                
                

                cv.imshow('img2', img2);

                img1.delete();
                img2.delete();
                // img3.delete();
                // dst.delete();
                contours.delete();
                hierarchy.delete();

            }
        }

        function loadImg(url) {
            return new Promise((resolve, reject) => {
                let img = new Image();
                // img.crossOrigin = ''; 
                // img.crossOrigin = 'anonymous';
                // 跨域 直接用live server运行 或者使用webview打开
                img.src = url;
                img.onload = () => {
                    resolve(img);
                };
                img.onerror = reject;
            });
        }
    </script>
</body>

</html>